﻿using MediatR;
using ProcurementManagement.Applcation.Command.ProcureEnquiryCommand;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.ProcureEnquiryCommandHandlers
{
    /// <summary>
    /// 采购供应商删除
    /// </summary>
    public class ProcureEnquiryDeleteCommandHandlers : IRequestHandler<ProcureEnquiryDeleteCommand, int>
    {
        protected readonly IProcureEnquiryRepository repository;
        protected readonly IInquiryVendorRepository vendorRepository;
        protected readonly ISqlSugarClient db;

        public ProcureEnquiryDeleteCommandHandlers(IProcureEnquiryRepository repository, IInquiryVendorRepository vendorRepository, ISqlSugarClient db)
        {
            this.repository = repository;
            this.vendorRepository = vendorRepository;
            this.db = db;
        }

        public async Task<int> Handle(ProcureEnquiryDeleteCommand request, CancellationToken cancellationToken)
        {
            db.Ado.BeginTran();
            try
            {
                foreach (var item in request.ids)
                {
                    var peList = (await repository.GetAll()).First(x => x.ProcureEnquiryId == item);
                    peList.IsDel = true;
                    peList.DelName = request.DelName;
                    peList.DelTime = DateTime.Now;
                    await repository.UpdataAsync(peList);
                    //删除供应商关联表
                    var vendor = (await vendorRepository.GetAll()).Where(x => x.PEDocumentsNumber == peList.PEDocumentsNumber).ToList();
                    foreach (var item1 in vendor)
                    {
                        var vendorList = (await vendorRepository.GetAll()).First(x => x.InquiryVendorid == item1.InquiryVendorid);
                        vendorList.IsDel = true;
                        vendorList.DelName = request.DelName;
                        vendorList.DelTime = DateTime.Now;
                        await vendorRepository.UpdataAsync(vendorList);
                    }
                }

                db.Ado.CommitTran();
                return 1;

            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }


        }
    }
}
